package com.cz.nongyetongv5.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.BeiJianDanWei;
import com.cz.nongyetongv5.bean.ChanPinLeiBie;
import com.cz.nongyetongv5.bean.ChouYanJiGou;
import com.cz.nongyetongv5.bean.JianCeFangFa;
import com.cz.nongyetongv5.bean.JianCeLeiBie;
import com.cz.nongyetongv5.bean.JianCeYiJu;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaHangYe;
import com.cz.nongyetongv5.bean.JianChaNeiRong;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.LinkMan;
import com.cz.nongyetongv5.bean.RenWuLaiYuan;
import com.cz.nongyetongv5.bean.Town;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class InitDataUtil {

	private Context context;

	/**
	 * 最后修改的时间
	 */
	private String modify_time = null;

	private DatabaseHelper db = null;

	public InitDataUtil(DatabaseHelper db, Context context) {
		this.db = db;
		this.context = context;
	}

	// 递归读取JSON
	private void readJson(JSONObject jsonObject, List<Object> towns) {

		// 读取所有的key
		Iterator<String> keys = jsonObject.keys();

		while (keys.hasNext()) {
			// 如果存在key
			String key = keys.next();

			// 数据读取

			try {

				if (CharsetUtil.isNotNull(key)) {
					// 读取内容
					JSONObject childObject = jsonObject.getJSONObject(key);

					String code = childObject.getString("code");

					String parent_code = null;

					if (!"null".equals(childObject.getString("parent_code"))) {
						parent_code = childObject.getString("parent_code");
					}

					String name = childObject.getString("name");

					Town town = new Town(code, parent_code, name, modify_time);

					if (childObject.isNull("cell")
							&& town.getCode().toString().length() <= 6) {

					} else {
						towns.add(town);
					}

					if (!childObject.isNull("cell")) {
						JSONObject cell = childObject.getJSONObject("cell");
						readJson(cell, towns);
					}

				}

			} catch (JSONException e) {
			}
		}

	}

	/**
	 * 下载乡镇
	 */
	public void downloadTown() throws Exception {
		if (db.queryTableCount("TOWN") < 1) {
			// 下载城镇的
			String downloadTownUrl = context.getResources().getString(
					R.string.download_towninfo);

			downloadTownUrl = new ConfigUtil(context.getResources())
					.getPreHttpUrl() + downloadTownUrl;

			List<Object> towns = new ArrayList<Object>();

			String json = ImageUtil.getJsonByName(
					context.getApplicationContext(), "towns_json");

			JSONObject jsonObject = new JSONObject(json);

			modify_time = jsonObject.getJSONObject("modified").getString(
					"datetime");

			readJson(jsonObject.getJSONObject("result"), towns);

			db.insertTown(towns);
		}

	}

	/**
	 * 下载检查行业
	 */
	public void downloadJianChaHangYe() throws Exception {

		if (db.queryTableCount("JIANCHAHANGYE") < 1) {

			List<Object> jianChaHangYes = new ArrayList<Object>();

			String json = ImageUtil.getJsonByName(
					context.getApplicationContext(), "jianchahangye_json");

			JSONArray jsonArray = new JSONArray(json);

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject item = jsonArray.getJSONObject(i);

				Integer id = item.getInt("value");

				String name = item.getString("name");

				jianChaHangYes.add(new JianChaHangYe(id, name));

			}

			db.insertJianChaHangYe(jianChaHangYes);

		}
	}

	/**
	 * 下载检查内容
	 */
	public void downloadJianChaNeiRong() throws Exception {

		if (db.queryTableCount("JIANCHANEIRONG") < 1) {

			List<Object> jianChaNeiRongs = new ArrayList<Object>();

			String json = ImageUtil.getJsonByName(
					context.getApplicationContext(), "jianchaneirong_json");

			JSONArray jsonArray = new JSONArray(json);

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject item = jsonArray.getJSONObject(i);

				Integer id = item.getInt("value");

				String name = item.getString("name");

				jianChaNeiRongs.add(new JianChaNeiRong(id, name));

			}
			;

			db.insertJianChaNeiRong(jianChaNeiRongs);
		}
	}

	/**
	 * 下载被检单位
	 */
	public void downloadBeiJianDanWei() throws Exception {

		// 清理表
		db.dropTableName("BEIJIANDANWEI", R.string.table_beijiandanwei);

		List<Object> beiJianDanWeis = new ArrayList<Object>();

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"beijiandanweiInfo_json");

		JSONObject jsonObject = new JSONObject(json);

		String time = jsonObject.getJSONObject("modified")
				.getString("datetime");

		JSONArray jsonArray = jsonObject.getJSONArray("result");

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject jsonDataObj = jsonArray.getJSONObject(i);

			if (!jsonDataObj.isNull("name")) {

				String id = jsonDataObj.getString("id");

				String name = jsonDataObj.getString("name");

				String code = jsonDataObj.getLong("region_code") + "";

				Integer kind = jsonDataObj.getInt("kind");

				double longitude = jsonDataObj.getDouble("longitude");

				double latitude = jsonDataObj.getDouble("latitude");

				String category = null;

				if (!jsonDataObj.isNull("category")) {
					category = jsonDataObj.getString("category");
				}

				String tel = jsonDataObj.getString("tel");

				String mobile = null;

				if (!jsonDataObj.isNull("mobile")) {
					mobile = jsonDataObj.getString("mobile");
				}

				String address = jsonDataObj.getString("address");

				String charge = jsonDataObj.getString("charge");

				BeiJianDanWei beiJianDanWei = new BeiJianDanWei(id, name, code,
						time, time, time, address, kind, longitude, latitude,
						category, charge, tel, mobile);

				beiJianDanWeis.add(beiJianDanWei);
			}

		}

		db.insertBeiJianDanWei(beiJianDanWeis);

	}

	/**
	 * 下载检查单位
	 */
	public void downloadJianChaDanWei() throws Exception {
		db.dropTableName("JIANCHADANWEI", R.string.table_jianchadanwei);

		List<Object> jianChaDanWeis = new ArrayList<Object>();

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"jianchadanweiInfo_json");

		JSONObject jsonObject = new JSONObject(json);

		String time = jsonObject.getJSONObject("modified")
				.getString("datetime");

		JSONArray jsonArray = jsonObject.getJSONArray("result");

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject jsonDataObject = jsonArray.getJSONObject(i);

			if (!jsonDataObject.isNull("id")) {

				String id = jsonDataObject.getString("id");

				String name = jsonDataObject.getString("name");

				String region_code = jsonDataObject.getLong("region_code") + "";

				JianChaDanWei jianChaDanWei = new JianChaDanWei(id, name,
						region_code, time, time, time);

				jianChaDanWeis.add(jianChaDanWei);

			}

		}

		db.insertJianChaDanWei(jianChaDanWeis);

	}

	/**
	 * 下载检查人员
	 */
	public void downloadJianChaRenYuan() throws Exception {

		db.dropTableName("JIANGUANRENYUAN", R.string.table_jianguanrenyuan);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"jiancharenyuan_json");

		JSONObject jsonObject = new JSONObject(json);

		String time = jsonObject.getJSONObject("modified")
				.getString("datetime");

		JSONArray jsonArray = jsonObject.getJSONArray("result");

		List<Object> jianChaRenYuans = new ArrayList<Object>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject jsonDataObject = jsonArray.getJSONObject(i);

			if (!jsonDataObject.isNull("id")) {

				String id = jsonDataObject.getString("id");

				String name = jsonDataObject.getString("realname");

				Integer rank = jsonDataObject.getInt("rank");

				String region_code = jsonDataObject.getLong("region_code") + "";

				JianChaRenYuan jianChaRenYuan = new JianChaRenYuan(id, name,
						rank, region_code, time, time, time);

				jianChaRenYuans.add(jianChaRenYuan);
			}

		}

		db.insertJianChaRenYuan(jianChaRenYuans);

	}

	/**
	 * 下载联系人
	 */
	public void downloadLinkMan() throws Exception {

		db.dropTableName("LINKMAN", R.string.table_linkman);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"linkman_json");

		JSONObject jsonObject = new JSONObject(json);

		JSONArray jsonArray = jsonObject.getJSONArray("result");

		String time = jsonObject.getJSONObject("modified")
				.getString("datetime");

		List<LinkMan> linkMans = new ArrayList<LinkMan>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject linkManObjJson = jsonArray.getJSONObject(i);

			String id = linkManObjJson.getString("id");

			String realName = linkManObjJson.getString("realname");

			Integer sex = linkManObjJson.getInt("sex");

			String tel = linkManObjJson.getString("tel");

			String mobile = linkManObjJson.getString("mobile");

			String departmentName = linkManObjJson.getString("department_name");

			String post = linkManObjJson.getString("post");

			Integer rank = linkManObjJson.getInt("rank");

			Double longitude = linkManObjJson.getDouble("longitude");

			Double latitude = linkManObjJson.getDouble("latitude");

			String regionCode = linkManObjJson.getLong("region_code") + "";

			LinkMan linkMain = new LinkMan(id, realName, sex, tel, mobile,
					departmentName, post, rank, longitude, latitude,
					regionCode, time, time, time);

			linkMans.add(linkMain);

		}

		db.insertLinkMan(linkMans);

	}

	/**
	 * 下载任务来源
	 */
	public void downloadRenWuLaiYuan() throws Exception {

		db.dropTableName("RENWULAIYUAN", R.string.table_renwulaiyuan);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"renwulaiyuan_json");

		JSONArray jsonArray = new JSONArray(json);

		List<RenWuLaiYuan> renWuLaiYuans = new ArrayList<RenWuLaiYuan>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			Integer id = renWuLaiYuanJsonObj.getInt("value");

			String name = renWuLaiYuanJsonObj.getString("name");

			Integer sortorder = renWuLaiYuanJsonObj.getInt("sortorder");

			RenWuLaiYuan renWuLaiYuan = new RenWuLaiYuan(id, name, sortorder);

			renWuLaiYuans.add(renWuLaiYuan);

		}

		db.insertRenWuLaiYuan(renWuLaiYuans);
	}

	/**
	 * 下载检测类别
	 */
	public void downloadJianCeLeiBie() throws Exception {

		db.dropTableName("JIANCELEIBIE", R.string.table_jianceleibie);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"jianceleibie_json");

		JSONArray jsonArray = new JSONArray(json);

		List<JianCeLeiBie> jianCeLeiBies = new ArrayList<JianCeLeiBie>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			Integer id = renWuLaiYuanJsonObj.getInt("value");

			String name = renWuLaiYuanJsonObj.getString("name");

			Integer sortorder = renWuLaiYuanJsonObj.getInt("sortorder");

			JianCeLeiBie renWuLaiYuan = new JianCeLeiBie(id, name, sortorder);

			jianCeLeiBies.add(renWuLaiYuan);

		}

		db.insertJianCeLeiBie(jianCeLeiBies);
	}

	/**
	 * 下载产品类别
	 */
	public void downloadChanPinLeiBie() throws Exception {

		db.dropTableName("CHANPINLEIBIE", R.string.table_chanpinleibie);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"chanpinleibie_json");

		JSONArray jsonArray = new JSONArray(json);

		List<ChanPinLeiBie> chanPinLeiBies = new ArrayList<ChanPinLeiBie>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			Integer id = renWuLaiYuanJsonObj.getInt("value");

			String name = renWuLaiYuanJsonObj.getString("name");

			Integer sortorder = renWuLaiYuanJsonObj.getInt("sortorder");

			chanPinLeiBies.add(new ChanPinLeiBie(id, name, sortorder));

		}

		db.insertChanPinLeiBie(chanPinLeiBies);
	}

	/**
	 * 下载检测方法
	 */
	public void downloadJianCeFangFa() throws Exception {

		db.dropTableName("JIANCEFANGFA", R.string.table_jiancefangfa);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"jiancefangfa_json");

		JSONArray jsonArray = new JSONArray(json);

		List<JianCeFangFa> jianCeFangFas = new ArrayList<JianCeFangFa>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			Integer id = renWuLaiYuanJsonObj.getInt("value");

			String name = renWuLaiYuanJsonObj.getString("name");

			Integer sortorder = renWuLaiYuanJsonObj.getInt("sortorder");

			JianCeFangFa renWuLaiYuan = new JianCeFangFa(id, name, sortorder);

			jianCeFangFas.add(renWuLaiYuan);

		}

		db.insertJianCeFangFa(jianCeFangFas);
	}

	/**
	 * 下载检测依据
	 */
	public void downloadChouYanJiGou(SQLiteDatabase db) throws Exception {

		// 第一版的时候才会清理数据库重新建表旦
		if (CommonConstants.DATABASE_VERSION == 1) {

			this.db.dropTableName("CHOUYANJIGOU", R.string.table_chouyanjigou);
		}

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"chouyanjigouInfo_json");

		JSONObject jsonObject = new JSONObject(json);

		String time = jsonObject.getJSONObject("modified")
				.getString("datetime");

		JSONArray jsonArray = jsonObject.getJSONArray("result");

		List<ChouYanJiGou> chouYanJiGous = new ArrayList<ChouYanJiGou>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			String id = renWuLaiYuanJsonObj.getString("id");

			String name = renWuLaiYuanJsonObj.getString("name");

			String code = renWuLaiYuanJsonObj.getLong("region_code") + "";

			String tel = null;

			if (!renWuLaiYuanJsonObj.isNull("tel")) {
				tel = renWuLaiYuanJsonObj.getString("tel");
			}

			ChouYanJiGou chouYanJiGou = new ChouYanJiGou(id, name, code, time,
					time, time, tel);

			chouYanJiGous.add(chouYanJiGou);

		}

		this.db.insertChouYangJiGou(chouYanJiGous, db);
	}

	/**
	 * 下载检测依据
	 */
	public void downloadJianCeYiJu() throws Exception {

		db.dropTableName("JIANCEYIJU", R.string.table_jianceyiju);

		String json = ImageUtil.getJsonByName(context.getApplicationContext(),
				"jianceyiju_json");

		JSONArray jsonArray = new JSONArray(json);

		List<JianCeYiJu> jianCeYiJus = new ArrayList<JianCeYiJu>();

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject renWuLaiYuanJsonObj = jsonArray.getJSONObject(i);

			Integer id = renWuLaiYuanJsonObj.getInt("value");

			String name = renWuLaiYuanJsonObj.getString("name");

			Integer sortorder = renWuLaiYuanJsonObj.getInt("sortorder");

			JianCeYiJu jianCeYiJu = new JianCeYiJu(id, name, sortorder);

			jianCeYiJus.add(jianCeYiJu);

		}

		db.insertJianCeYiJu(jianCeYiJus);
	}
}
